#include "CollectAllPCResultCmd.h"
#include <conio.h>
#include <wmi_constants.h>

using namespace std;

void CollectAllPCResultCmd::execute()
{

	wstring user(L"Administrator");
	wstring password(L"admin");
	wstring domain(L"venus.local");
	wstring serverName(L"VenusServer");

	bridget_communicator::initCom();

	// wcin >> user >> password >> domain ;

	vector<ADCM_Computer> *computers = new vector<ADCM_Computer>;
	bridget_communicator::getComputers(
		serverName,
		domain,
		user,
		password,*computers);
	// TODO: VALIDATE return
//	 bridget_communicator::save(serverName,domain,*computers);

	VNC_ComputerThread** pcThread =  new VNC_ComputerThread*[computers->size()];

	vector<ADCM_Computer>::iterator iter;
	int index = 0;
	
	ResultFormatter resFormatter;

	wstring emptyString (L"");
 
	for (iter = computers->begin(); iter != computers->end(); iter++)
	{				
		if((*iter).getCn().compare(L"VMMOBSPC") == 0){
		if (isLocalComputer((*iter).getCn()))
			pcThread[index] = new VNC_ComputerThread(resFormatter,*iter, emptyString, emptyString, emptyString,true);
		else pcThread[index] = new VNC_ComputerThread(resFormatter,*iter, user, password, domain,false);

		pcThread[index++]->Start(NULL);
		}
	}

	index = 0;
	while(true) 
	{ 
		// cout << "Al sleep" << endl;
		Sleep(10000);
		// cout << "Al Exit" << endl;
		 for (iter = computers->begin(); iter != computers->end(); iter++)
		 {
			 if (pcThread[index]!= NULL)
			 {
				 pcThread[index]->setExit(true);
			 }

			 index ++;
		 }
		// cout << "al break" << endl;
		 break;
		// cout << "despues del break" << endl;

	}

	index = 0;
	for (iter = computers->begin(); iter != computers->end(); iter++)
	{
		if (pcThread[index] != NULL)
		{
			pcThread[index]->Stop(true);
		}

		index ++;
	}

	Sleep(3000);

	bridget_communicator::closeCom();
}

bool CollectAllPCResultCmd::isLocalComputer(const wstring& pcName)
{
	bool res = false;

	const long INFO_BUFFER_SIZE = 100;

	TCHAR infoBuf[INFO_BUFFER_SIZE];
	DWORD bufCharCount = INFO_BUFFER_SIZE;

	GetComputerName(infoBuf, &bufCharCount);

	wstringstream a;
	a << infoBuf;

	wstring var(a.str().c_str());

	if(wcscmp(pcName.c_str(), var.c_str()) == 0)
		res = true;
	
	return res;
}